# Created by 黄景涛
# DATE: 2025/3/6
import yaml
import json
from copy import deepcopy

node_temp = {
    "key": "",
    "name": "",
    "rank": 0,
    "children": []
}


def transfer(option: dict):
    ans = deepcopy(node_temp)
    ans.update(key=option.get('key'), name=option.get('name'))

    def dfs(node: dict, new_node: dict):
        if not node['children']:
            return

        for i, child in enumerate(node.get('children')):
            chd = deepcopy(node_temp)
            chd.update(key=child.get('key'), name=child.get('name'), rank=i)
            new_node.get('children').append(chd)
            dfs(child, chd)

    dfs(option, ans)
    return ans


def get_new_data(old_data_file: str):
    with open(old_data_file, 'r', encoding='utf8') as f:
        old_data = yaml.safe_load(f)

    ans = {
        "app_id": "core",
        "key": old_data.get('key'),
        "name": old_data.get('value'),
        "desc": "",
        "tree_data": {
            "key": "",
            "name": "",
            "children": []
        }
    }

    for opt in old_data.get('choice'):
        new_option = transfer(opt)
        ans['tree_data']['children'].append(new_option)

    with open('new_data.json', 'w', encoding='utf8') as f:
        json.dump(ans, f, ensure_ascii=False)


if __name__ == '__main__':
    get_new_data('cascade_data.yaml')
